using CoreProject.IRepository;
using CoreProject.Model;
using Microsoft.EntityFrameworkCore;

namespace CoreProject.Repository
{
  internal class MenusRepository : BaseRepository<Menu>, IMenusRepository
  {
        private readonly EFDbContext _dbContext;

        public MenusRepository(EFDbContext dbContext) : base(dbContext)
    {
            this._dbContext = dbContext;
        }

        public async Task<bool> DeleteMenu(int id)
        {
            var zhi = await _dbContext.Menus.Where(n =>n.MenuId == id).FirstOrDefaultAsync();
            var hh = await _dbContext.Authorities.Where(n => n.MenuId == id).FirstOrDefaultAsync();
            if (hh != null)
            {
                _dbContext.Authorities.Remove(hh);
                _dbContext.Menus.Remove(zhi);
              
            }
            else
            {
                _dbContext.Menus.Remove(zhi);
              
            }
            return await _dbContext.SaveChangesAsync()>0;

        }

        public async Task<bool> DeleteMenus(int[] ids)
        {
            var zhi = _dbContext.Menus.Where(n =>ids.Contains(n.MenuId)).ToList();
            var hh = _dbContext.Authorities.Where(n =>ids.Contains(n.MenuId)).ToList();
            if (hh != null)
            {
                _dbContext.Authorities.RemoveRange(hh);
                _dbContext.Menus.RemoveRange(zhi);

            }
            else
            {
                _dbContext.Menus.RemoveRange(zhi);

            }
            return await _dbContext.SaveChangesAsync() > 0;
        }

        public async Task<List<Menu>> GetMenus()
    {
      return await _dbContext.Menus.Include(m => m.Authorities).ToListAsync();
    }

        public async Task<(List<Menu> list, int count)> GetMenusBypage(string name, int page, int size)
        {
            var data =await _dbContext.Menus.Include(m => m.Authorities).ToListAsync();
           
            if (!string.IsNullOrWhiteSpace(name)) {
                data = data.Where(n=>n.MenuName.Contains(name)).ToList() ;
            }
            int count=data.Count();
            var pagelist = data.OrderBy(n => n.MenuId).Skip((page - 1) * size).Take(size);
            return (pagelist.ToList(),count);
        }
    }
}
